
/* #include "LPC23xx.h" */
#include "SysClock.h"
#include "LPC23xx.h"
#include "sys_config.h"
#include "macros.h"
#include "OS.h"

volatile int SysTimer;
volatile int SysTimer_1;


volatile int Time_10ms;

static void SysClock_ISR_Handler ( void )
{
	
//	FIO2PIN ^= (1UL<<2);
	SysTimer++;
	SysTimer %= SYS_CLOCK_TIMER_0_MAX;
	
	Time_10ms = TRUE;

	//OS_App_Timers();

	T0IR = 1;			/* clear interrupt flag */

	VICVectAddr = 0;
}


void SysTimer_Init( unsigned int Interval )
{
	unsigned int TimerInterval;
	
	SysTimer = 0;
	
	T0PR = 0;

	TimerInterval = (unsigned int)(PCLK/1000UL);
	TimerInterval *= Interval;

	T0MR0 = TimerInterval -1;
	T0MCR = 3;				/* Interrupt and Reset on MR0 */
	T0IR = 1;			/* clear interrupt flag */

//	DBG_OUT("\rT0MR0: %u", T0MR0);

	VICIntSelect &= ~(1UL<<4); 					// choose IRQ 
	VICVectAddr4 = (unsigned int)SysClock_ISR_Handler;	// TMR0
	VICIntEnClr = (1UL<<4);
	VICVectPriority4 = 14;
	VICIntEnable = (1UL<<4);
	
	T0TCR = 1;						  /* timer start */
}

#if 0
static void Timer_1_ISR_Handler ( void )
{
//	i_Time_1 = TRUE;

	SysTimer_1++;
	SysTimer_1 %= SYS_CLOCK_1_TIMER_MAX;


	T1IR = 1;			/* clear interrupt flag */

	VICVectAddr = 0;
}

void Timer_1_Init( unsigned int Interval )
{
	unsigned int TimerInterval;
	
	
//	T1PR = (unsigned int)(PCLK/1000UL);

	TimerInterval = (unsigned int)(PCLK/1000UL);	/* 1 ms */
	TimerInterval *= Interval;

	T1MR0 = TimerInterval -1;
	T1MCR = 3;				/* Interrupt and Reset on MR0 */
	//T1MCR = 2;				/* Reset on MR0 */
	T1IR = 1;			/* clear interrupt flag */


	VICIntSelect &= ~(1UL<<5); 					// choose IRQ
	VICVectAddr5 = (unsigned int)Timer_1_ISR_Handler;	// TMR1
	VICIntEnClr = (1UL<<5);
	VICVectPriority5 = 15;
	VICIntEnable = (1UL<<5);
	
	T1TCR = 1;						  /* timer start */
}
#endif


unsigned int Sys_Time;

static unsigned int _Sys_Time;

void SysClock ( void )
{
	Sys_Time = 0;

	if ( Time_10ms )
	{
		Time_10ms = 0;

		_Sys_Time++;

		Sys_Time = _Sys_Time * SYS_CLOCK__TIMER_0_INTERVAL;
	} 
}
